package org.ns.longhttp.wrapper;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.http.cookie.DefaultCookie;
import org.ns.longhttp.ResponseUtil;

import java.nio.charset.Charset;
import java.util.List;

/**
 * GET 请求包装
 */
public class GetRequestWrapper {

    private FullHttpRequest request; // 客户端的请求
    private ChannelHandlerContext ctx; // 面对客户端的通道
    private String url; // url
    private long dataid; // 数据ID
    private UrlParameterMap urlParameterMap;
    public GetRequestWrapper(FullHttpRequest request, ChannelHandlerContext ctx, String url, long dataid) {
        this.request = request;
        this.ctx = ctx;
        this.url = url;
        this.dataid = dataid;
        this.urlParameterMap = new UrlParameterMap(request);
    }

    public void write(GetResponseWrapper responseWrapper) {
        String callback = urlParameterMap.getParameter("callback");
        String json = responseWrapper.toJson(callback);
        ByteBuf content = ctx.alloc().buffer();
        content.writeCharSequence(json, Charset.forName("UTF-8"));

        String contentType = "application/json;charset=UTF-8";
        if (callback != null && !callback.isEmpty()) {
            contentType = "application/javascript;charset=UTF-8";
        }

        HttpHeaders headers = new DefaultHttpHeaders();
        DefaultCookie cookie = new DefaultCookie("id", String.valueOf(responseWrapper.getLastId()));
        String cookieValue = ResponseUtil.getCookie(cookie);
        if (cookieValue != null) {
            // System.out.println("cookie:" + cookieValue);
            headers.add(HttpHeaderNames.SET_COOKIE, cookieValue);
        }
        headers.set(HttpHeaderNames.CONTENT_TYPE, contentType);
        ResponseUtil.write(ctx, request, content, headers);
    }

    public void write(ByteBuf content, String contentType) {
        HttpHeaders headers = new DefaultHttpHeaders();
        headers.set(HttpHeaderNames.CONTENT_TYPE, contentType);
        ResponseUtil.write(ctx, request, content, headers);
    }

    public void write() {
        HttpHeaders headers = new DefaultHttpHeaders();
        headers.set(HttpHeaderNames.CONTENT_LENGTH, 0);
        ResponseUtil.write(ctx, request, null, headers);
    }

    public boolean isInvalid() {
        return ctx.isRemoved() || !ctx.channel().isWritable();
    }

    public String getUrl() {
        return url;
    }

    public int getAwaitTimeout(int defaultValue) {
        HttpHeaders headers = request.headers();
        return headers.getInt("Await_Timeout", defaultValue);
    }

    public long getDataid() {
        return dataid;
    }
}
